# -*- coding:utf-8 -*-
import logging
from urllib.parse import urljoin

from celery import Celery, platforms
from flask import Flask
from flask import Markup
from flask_cache import Cache
from flask_mail import Mail
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_sitemap import Sitemap
import markdown2
from app.config import config, Config
from flask_apidoc import ApiDoc

mail = Mail()
db = SQLAlchemy()
cache = Cache()
celery = Celery(__name__, broker=Config.CELERY_BROKER_URL,backend=Config.CELERY_RESULT_BACKEND)
platforms.C_FORCE_ROOT = True
session = Session()
sitemap = Sitemap()


def neomarkdown(markdown_content):
    content = Markup(markdown2.markdown(markdown_content, extras=["tables"]))
    return content


def get_favicon(url):
    return urljoin(url, '/favicon.ico')


# 工厂函数
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    mail.init_app(app)
    db.init_app(app)
    cache.init_app(app, config)
    app.jinja_env.variable_start_string = '<< '
    app.jinja_env.variable_end_string = ' >>'
    app.jinja_env.block_start_string='<%'
    app.jinja_env.block_end_string = '%>'
    app.jinja_env.comment_start_string = '<#'
    app.jinja_env.comment_end_string = '#>'
    session.init_app(app)
    celery.conf.update(app.config)
    #socketio.init_app(app=app, message_queue=config[config_name].REDIS_URI,async_mode=None)
    # 注册蓝本
    from app.views import main as main_blueprint
    from app.views import admin as admin_blueprint
    app.register_blueprint(main_blueprint)
    app.register_blueprint(admin_blueprint)
    # 注册自定义过滤器
    env = app.jinja_env
    env.filters['neomarkdown'] = neomarkdown
    env.filters['get_favicon'] = get_favicon
    handler = logging.FileHandler('log/flask.log', encoding='UTF-8')  # 设置日志字符集和存储路径名字
    logging_format = logging.Formatter(                            # 设置日志格式
        '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
    handler.setFormatter(logging_format)
    app.logger.addHandler(handler)
    ext.init_app(app)
    return app